package tankgame02;

import java.util.Vector;

public class EnemyTank extends Tank implements Runnable {

	Vector<Shot> shots = new Vector<>();

	public EnemyTank(int x, int y) {
		super(x, y);
	}

	@Override
	public void run() {
		while (true) {
			//这里我们判断如果敌人的子弹为空，就为他增加一颗子弹
			if (isLive && shots.size() == 0) {
				Shot shot = null;
				switch (getDirection()) {
					case 0:
						shot = new Shot(getX() + 20, getY(), 0);
						break;
					case 1:
						shot = new Shot(getX() + 60, getY() + 20, 1);
						break;
					case 2:
						shot = new Shot(getX() + 20, getY() + 60, 2);
						break;
					case 3:
						shot = new Shot(getX(), getY() + 20, 3);
						break;
				}
				shots.add(shot);
				new Thread(shot).start();
			}

			//根据坦克的方向来继续移动
			switch (getDirection()) {
				case 0:
					//让坦克保持一个方向走三十下
					for (int i = 0; i < 30; i++) {
						if (getY() > 0) {
							moveUp();
						}
						//休眠50ms
						try {
							Thread.sleep(50);
						} catch (
								InterruptedException e) {
							throw new RuntimeException(e);
						}
					}
					break;
				case 1:
					for (int i = 0; i < 30; i++) {
						if (getX() + 60 < 1000) {
							moveRight();
						}
						//休眠50ms
						try {
							Thread.sleep(50);
						} catch (
								InterruptedException e) {
							throw new RuntimeException(e);
						}
					}
					break;
				case 2:
					for (int i = 0; i < 30; i++) {
						if (getY() + 60 < 750) {
							moveDown();
						}
						//休眠50ms
						try {
							Thread.sleep(50);
						} catch (
								InterruptedException e) {
							throw new RuntimeException(e);
						}
					}
					break;
				case 3:
					for (int i = 0; i < 30; i++) {
						if (getX() > 0) {
							moveLeft();
						}
						//休眠50ms
						try {
							Thread.sleep(50);
						} catch (
								InterruptedException e) {
							throw new RuntimeException(e);
						}
					}
					break;
			}


			//然后随机改变坦克方向
			setDirection((int) (Math.random() * 4));
			//写并发程序，一定要考虑清楚什么时候结束
			if (!isLive) {//不存活
				break;
			}
		}
	}
}
